<?php

declare(strict_types=1);

namespace So\App\Controller\Backend;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;
use So\Controller\Backend;
use So\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use So\Annotation\Auth;
use So\App\Model\Backend\AuthRule;
use So\Exception\ControllerException;
use So\Library\Tree;
use So\Library\Auth as AuthLib;
use Hyperf\Di\Annotation\Inject;
use So\Annotation\Validation;
use So\Annotation\Model;
use So\Annotation\AdminLog;

/**
 * @Controller(prefix="auth_rule")
 * @Auth
 * @AdminLog({"auth_rule/create"})
 */
class AuthRuleController extends Backend
{
    /**
     * @Inject()
     * @var AuthLib
     */
    protected $auth;

    /**
     * @GetMapping("read")
     */
    public function read($model): ResponseInterface
    {
        $data = Tree::instance()->init(AuthRule::query()->orderBy('sort', 'desc')->get())->getVueMenuList(0, 0, true);
        return $this->success('', $data['menuList']);
    }

    /**
     * @PostMapping("create")
     * @Validation
     * @Model
     */
    public function create($data, $model): ResponseInterface
    {
        return parent::create($data, $model);
    }

    /**
     * @DeleteMapping("delete")
     * @Validation
     * @Model
     */
    public function delete($data, $model): ResponseInterface
    {
        return parent::delete($data, $model);
    }

    /**
     * @PostMapping("sort")
     * @Model
     */
    public function sort($model): ResponseInterface
    {
        return parent::draggable($model);
    }

    /**
     * @PutMapping("update")
     * @Validation
     * @Model
     */
    public function update($data, $model): ResponseInterface
    {
        return parent::update($data, $model);
    }

    protected function _create($data, $model)
    {
        $data = $this->_pid($data, $model);
        if ($data['pid'] == 0) {
            $sort = $model::query()->where('pid', '=', 0)->orderBy('sort', 'asc')->first();
            $data['sort'] = $sort ? $sort['sort'] - 50 : 50;
        } else {
            $sort = $model::query()->orderBy('sort', 'desc')->first();
            $data['sort'] = $sort ? $sort['sort'] + 50 : 50;
        }
        return $data;
    }

    protected function _update($data, $model)
    {
        return $this->_pid($data, $model);
    }

    protected function _delete($ids, $model)
    {
        return array_merge($ids, $model->getChildPk($ids));
    }

    private function _pid($data, $model)
    {
        $pid = $data['pid'];
        if (is_array($pid)) {
            $pid = end($pid);
            $res = $model::query()->find($pid);
            if (!$res) {
                throw new ControllerException('上级不存在');
            }
            $data['pid'] = $pid;
        }

        return $data;
    }
}